<template>
	<hx-navbar title="确认订单" />
	<view class="order-confirm-container" v-if="!loading">
		<!-- 配送方式 -->
		<view class="order-confirm-header">
			<u-radio-group v-model="state.deliveryWay" @change="deliveryWayChange">
				<u-radio name="1">普通快递</u-radio>
				<u-radio name="2">上门自提</u-radio>
			</u-radio-group>
			<u-cell-group :border="false" v-if="state.deliveryWay === '1'" class="user-address">
				<u-cell-item icon="map" :title-style="titleStyle" :border-bottom="false"
					:title="selectedAddress?.detailAddress || '请选择收货地址'"
					:label="selectedAddress?.recipientName + '  ' + selectedAddress?.telephone || ''"
					@click="toAddress" />
			</u-cell-group>
		</view>

		<!-- 订单商品内容 -->
		<view class="order-confirm-content">
			<view class="order-confirm-warp" v-for="(goods, index) in state.orderInfo.orderItemList" :key="index">
				<image :src="goods.picUrl" />
				<view class="right">
					<view class="goods-title">{{ goods.spuName }}</view>
					<view class="goods-spec">{{ goods.specsInfo }}</view>
					<view class="goods-price">
						<view class="text-price">{{ goods.salesPrice }}</view>
						<view class="goods-quantity">x{{ goods.buyQuantity }}</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 结算区域 -->
		<view class="order-confirm-settlement">
			<view class="order-confirm-settlement-warp">
				<view class="item">
					<view class="title"> 价格明细 </view>
				</view>
				<view class="item">
					<view class="title">商品总额</view>
					<view class="text-price">{{ state.orderInfo.totalPrice }}</view>
				</view>
				<view class="item">
					<view class="title">应付运费</view>
					<view class="text-price">{{ state.orderInfo.freightPrice }}</view>
				</view>
				<view class="item">
					<view class="title">优惠券</view>
					<view v-if="state.orderInfo.couponUserId" style="display: flex">
						- <view class="text-price" @click="showCoupon(state.orderInfo)">
							{{ state.orderInfo.couponPrice }} <u-icon name="arrow-right" size="26" />
						</view>
					</view>
					<view v-else-if="couponState.couponUserList.length > 0" @click="showCoupon(state.orderInfo)">
						选择优惠券 <u-icon name="arrow-right" size="26" />
					</view>
					<view v-else class="u-font-12">无可用优惠券</view>
				</view>
				<view class="total-price">
					合计：<text class="text-price">{{ state.orderInfo.paymentPrice }}</text>
				</view>
			</view>
		</view>

		<u-gap height="150" />

		<!-- 底部按钮 -->
		<view class="order-confirm-navigation">
			<view class="order-confirm-navigation-warp">
				<view class="left">
					<view class="text-price">{{ state.orderInfo.paymentPrice }}</view>
				</view>
				<view class="right">
					<u-button type="error" size="medium" shape="circle" @click="toPay">立即支付</u-button>
				</view>
			</view>
		</view>

		<!-- 领券弹窗 -->
		<u-popup v-model="couponState.couponPopup" mode="bottom" :safe-area-inset-bottom="true" :border-radius="20"
			:closeable="true" height="500px">
			<view style="margin-top: 40px">
				<CouponConfirm v-if="couponState.couponUserList.length > 0" :checkedCouponId="couponState.couponUserId"
					:list="couponState.couponUserList" :price="couponState.orderPrice" @confirm="couponConfirm" />
			</view>
			<u-gap height="200" />
			<view class="confirm-btn">
				<u-button type="primary" @click="onCouponConfirm">确认</u-button>
			</view>
		</u-popup>
	</view>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { storeToRefs } from 'pinia';
import { useGoodsStore } from '@/stores/goods';
import { getDefault } from '@/api/user/address';
import { getPage as getCouponList } from '@/api/promotion/couponUser';
import { orderCreate, orderSettlement } from '@/api/order/orderInfo';
import CouponConfirm from '@/components/coupon-confirm/index.vue';

const titleStyle = ref({ fontWeight: '700' });
const loading = ref(false);

const selectedAddress = ref({ id: '', detailAddress: '', recipientName: '', telephone: '' });
const storesGoodsStore = useGoodsStore();
const { goodsList }: any = storeToRefs(storesGoodsStore);

const state = reactive({
	orderInfo: {
		orderItemList: [],
		totalPrice: 0,
		freightPrice: 0,
		couponPrice: 0,
		paymentPrice: 0,
		couponUserId: '',
	},
	deliveryWay: '1',
	createWay: '2',
	skuList: []
});

const couponState = reactive({
	couponUserList: [],
	orderPrice: 0,
	couponPopup: false,
	currentShopId: '',
	couponUserId: '',
});

onLoad((options) => {
	state.createWay = options?.createWay || '2';
	initData();
	getDefaultAddress();
	getCoupon();
});

const initData = () => {
	loading.value = true;
	state.skuList = goodsList.value.map((item: any) => ({
		spuId: item.spuId,
		picUrl: item.picUrl,
		spuName: item.spuName,
		quantity: item.quantity,
		specsInfo: item.specsInfo,
		skuId: item.skuId,
	}));
	toSettlement();
};

const getDefaultAddress = () => {
	getDefault().then((res) => {
		selectedAddress.value = res.data || {};
	});
};

const toSettlement = () => {
	const orderReqParams = {
		deliveryWay: state.deliveryWay,
		orderType: '1',
		createWay: state.createWay,
		skuReqList: state.skuList,
		couponUserId: couponState.couponUserId || '',
	};
	orderSettlement(orderReqParams)
		.then((res) => {
			state.orderInfo = res.data;
		})
		.catch(() => {
			uni.$u.toast('订单结算失败');
		})
		.finally(() => {
			loading.value = false;
		});
};

const getCoupon = () => {
	getCouponList({ status: '0' }).then((res) => {
		couponState.couponUserList = res.data.records || [];
	});
};

const showCoupon = (item: any) => {
	couponState.couponUserId = item.couponUserId || '';
	couponState.orderPrice = item.totalPrice;
	couponState.couponPopup = true;
};

const couponConfirm = (couponUserId: string) => {
	if (couponUserId) {
		couponState.couponUserId = couponUserId;
		state.orderInfo.couponUserId = couponUserId;
	}
};

const onCouponConfirm = () => {
	couponState.couponPopup = false;
	toSettlement();
};

const deliveryWayChange = () => {
	toSettlement();
};

const toPay = () => {
	if (state.deliveryWay === '1' && !selectedAddress.value?.id) {
		return uni.$u.toast('请选择收货地址');
	}
	const order = {
		deliveryWay: state.deliveryWay,
		userAddressId: selectedAddress.value.id || '',
		orderType: '1',
		skuReqList: state.skuList,
		createWay: state.createWay,
		couponUserId: couponState.couponUserId || '',
	};
	orderCreate(order).then((res) => {
		uni.$hxRouter.push({
			type: 'redirectTo',
			url: `/pages/order/order-pay/index?id=${res.data.id}`,
		});
	});
};

const toAddress = () => {
	uni.$hxRouter.push({ url: '/pages/user/address/index?placeChooseFlag=true' });
};

uni.$on('update:selectedAddress', (newAddress) => {
	selectedAddress.value = newAddress;
});

uni.$once('beforeUnload', () => {
	uni.$off('update:selectedAddress');
});
</script>
<style lang="scss">
.confirm-btn {
	position: fixed;
	bottom: 0;
	width: 100%;
	border-top: 1px solid #eee;
	background-color: #fff;
	padding: 20rpx;
	padding-bottom: calc(env(safe-area-inset-bottom) + 20rpx);
	z-index: 999;
	box-shadow: 0 -4rpx 10rpx rgba(0, 0, 0, 0.05);
}

.order-confirm-container {
	padding: 20rpx;

	.order-confirm-header {
		background-color: #fff;
		padding: 20rpx;
		border-radius: 12rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);

		.user-address {
			margin-top: 20rpx;
		}
	}

	.order-confirm-content {
		margin-top: 20rpx;

		.order-confirm-warp {
			display: flex;
			background-color: #fff;
			border-radius: 12rpx;
			padding: 20rpx;
			box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.03);

			image {
				width: 160rpx;
				height: 160rpx;
				border-radius: 8rpx;
				object-fit: cover;
				flex-shrink: 0;
			}

			.right {
				flex: 1;
				margin-left: 20rpx;
				display: flex;
				flex-direction: column;
				justify-content: space-between;

				.goods-title {
					font-size: 28rpx;
					font-weight: 500;
					color: #333;
				}

				.goods-spec {
					font-size: 24rpx;
					color: #888;
					margin-top: 8rpx;
				}

				.goods-price {
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin-top: 12rpx;

					.text-price {
						color: #e93323;
						font-weight: bold;
					}
				}
			}
		}
	}

	.order-confirm-settlement {
		.order-confirm-settlement-warp {
			background-color: #fff;
			margin-top: 20rpx;
			padding: 20rpx;
			border-radius: 12rpx;
			box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);

			.item {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 16rpx 0;

				.title {
					font-size: 28rpx;
					color: #333;
				}

				.text-price {
					font-size: 28rpx;
					font-weight: 500;
				}
			}

			.total-price {
				display: flex;
				justify-content: flex-end;
				align-items: center;
				font-size: 30rpx;
				font-weight: bold;
				color: #e93323;
				padding-top: 20rpx;
			}
		}
	}

	.order-confirm-navigation {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		background-color: #fff;
		border-top: 1px solid #eee;
		padding: 20rpx;
		padding-bottom: calc(env(safe-area-inset-bottom) + 20rpx);
		box-shadow: 0 -4rpx 10rpx rgba(0, 0, 0, 0.05);
		z-index: 999;

		&-warp {
			display: flex;
			justify-content: space-between;
			align-items: center;

			.left .text-price {
				color: #e93323;
				font-size: 36rpx;
				font-weight: bold;
			}
		}
	}
}
</style>
